<template>
  <div class="app-container">
    <div class="app-title">
      <span>单位信息编辑</span>
    </div>
    <!-- 预算单位的蓝色按钮的位置 -->
    <el-row :gutter="20">
      <el-col :span="8">
      </el-col>
      <div class="filter-container">
        <div>
          <el-col
            style="text-align:right;margin-top: -8px;"
            :span="23"
          >
            <el-input v-model="batchSerchAgencyCode" 
              placeholder="请输入单位编码或名称过滤"
              
            />
          <el-date-picker v-model="selectMonth" 
              type="month" 
              placeholder="--请选择年月--"  
              @change="jobSearch"
               value-format="yyyy-MM">
            </el-date-picker>

            <el-button
              size="small"
              class="filter-item"
              style="margin-left: 10px;margin-top: 6px; "
              type="primary"
              @click="handleEdit"
            >
              同步
            </el-button>
            <el-button
              size="small"
              class="filter-item"
              style="margin-left: 10px;margin-top: 6px; "
              type="primary"
              @click="outPutFile"
            >
              模板导出
            </el-button>
            <el-button
              size="small"
              class="filter-item"
              style="margin-left: 10px;margin-top: 6px; "
              type="primary"
              @click="importFile"
            >
              导入
            </el-button>
          </el-col>
        </div>
      </div>
    </el-row>
    <div class="grid-content bg-purple" />
        <!-- 表格部分 -->
        <el-table
          ref="singalTable"
          v-loading="listLoading"
          :height="tableHeight"
          :data="lists"
          :stripe="true"
           row-key="id"
           border
           default-expand-all
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        
        >
          <!-- 调用 组件empty    根据数据条数生成序号-->
          <template slot="empty">
            <tableEmpty />
          </template>
          <el-table-column type="selection" align="center" width="50" :selectable="selectable"/>
          <el-table-column type="index" align="center" width="50" label="序号" />
          <!-- 将内容  row  去点 属性-->
          <el-table-column label="单位编码" align="center" prop="code">
            <template slot-scope="{row}">
              <span style="float: ">{{ row.code }}</span>
            </template>
          </el-table-column>
          <el-table-column label="单位名称" align="center" prop="label">
            <template slot-scope="{row}">
              <span style="float: ">{{ row.label }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center">
            <template slot-scope="{row}">
              <!--一个 判断的写法  根据 id 判断 -->
              <span style="float: ">{{ row.yesNo == 0? "已同步":"未同步" }}</span>
            </template>
          </el-table-column>
        </el-table>
        <!-- total 是条数的意思  page是当前内容数量    limit 是当前固定多少调 以及翻页   getList页面数据  -->
      <Drag ref="icon" />

      <el-dialog
      v-dialogDrag
      :close-on-click-modal="false"
      title="导入"
      :visible.sync="dialogImportFormVisible"
      width="29%"
    >
      <el-upload
        class="upload-demo"
        drag
        style="padding-left: 2px"
        action="#"
        list-type="multipart/form-data"
        accept=".xls,.xlsx"
        :show-file-list="false"
        :http-request="uploadExcel"
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip" />
      </el-upload>
    </el-dialog>

    </div>
    
    <!-- 编辑页面部分 -->
</template>
<script>
import { outPutProvinceReportList, provinceImport } from "@/api/unitSalaryReport/unitSalaryReport";
import { getAgency, insertAgencyLnIt } from '@/api/salaryConfigManage/agencyInit'
import Pagination from '@/components/Pagination'
import Enclosure from '@/components/Enclosure'
import tableEmpty from '@/components/table/empty'
import AgencyTree from '@/components/tree/agencyTree'
import Drag from '@/components/Drag'
export default {
  components: { Enclosure, Pagination, tableEmpty, AgencyTree, Drag },
  // filters: {
  //   bankFilters(type, that) {
  //     const agencyTypeList = that.agencyTypeList
  //     for (const item in agencyTypeList) {
  //       if (agencyTypeList[item].code === type) {
  //         return agencyTypeList[item].name
  //       }
  //     }
  //   }
  // },
  data() {
    return {
      selectMonth:'',
      treeHeight: null,
      isActive: true,
      tableHeight: null,
      Show: false,
      selection: [],
      treeShow: false,
      that: this,
      list: null,
      listLoading: true,
      saveLoading: false,
      dialogImportFormVisible: false,
      listQuery: {
        page: 1,
        limit: 200,
        agencyId: '',
        state: 0
      },
      formDsiabled: false,
      formData: {
        id: '',
        agencyId: '',
        agencyCode: '',
        agencyName: '',
        mofDivCode: '',
        meritPayId: '',
        meritPayName: '',
        meritPayCode: '',
        personNum: ''
      },
      dialogVerifyFormVisible: false,
      verifyLoading: false,
      dialogStatus: '',
      mofDivLists: ' ',
      editTableListLoading: false,
      agencyTypeList: '',
      batchSerchAgencyCode: '',
      addItem: {
        postId: '',
        isNewItem: ''
      },
      modifyList: [],
      editListData: [],
      agencyId: ' '
    }
  },
   computed: {  
    lists: function() {
      var search = this.batchSerchAgencyCode  
      if (search) {
        return this.list[0].children.filter(function(dataNews) {
          return Object.keys(dataNews).some(function(key) {
         
            if (key === 'code'|| key === 'label') {
             return String(dataNews[key]).indexOf(search) > -1
            } 
          })
        })
      }
      // debugger
      return this.list
    }
  },
  watch: {
    // 表格的数据数组
    list(val) {
      this.doLayout()
    }
  },
  // 加载后运行
  created() {
    // 获取 page 数据
    this.getList()
 
  },
  // 路由钩子 般在初始化页面完成后，再对dom节点进行相关操作
  mounted() {
    this.getTbHeight()
    this.dragController()
  },
  beforeMount() {
    window.addEventListener('resize', this.getTbHeight)
  },
  methods: {
    bindSelectChange() {
      //  获取 当前 editListData 里的 code值
      const tempList = this.editListData.map(item => item.meritPayCode)
      this.agencyTypeList.forEach(item => {
        // 判断 当前code 里是否被选择 选择就不可再次选择,避免重复
        tempList.includes(item.meritPayCode) ? item.disabled = true : item.disabled = false
      })
    },
    // 拖拽
    dragController() {
      this.$refs.icon.dragControllerDiv()
    },
    /* 重新渲染table组件 */
    doLayout() {
      this.$nextTick(() => {
        this.$refs.singalTable.doLayout()
      })
    },
    // 获取table高度的方法
    getTbHeight() {
      this.tableHeight = window.innerHeight - 220
      this.treeHeight = this.tableHeight
    },
    
    // 一个gitList 方法
    getList() {
      // 加载的时候 转圈圈
      this.listLoading = true
      // page 查询 接口
      getAgency().then(response => {
        // 将放回 的数据 赋值给list
        this.list = response.data 
        // 加载的时候 数据完毕后 转圈圈停止
        this.listLoading = false
      }).catch(() => {
        // list 是一个集合数组
        this.list = []
        // total 默认为0
        this.total = 0
        // 加载的时候 数据完毕后 转圈圈停止
        this.listLoading = false
      })
    },
    
    // 编辑
    handleEdit() {
      // 获取当前 表格信息中的 序号
      const selection = this.$refs.singalTable.selection
      // 判断当前序号是否等于你
     if (selection.length === 0) {
        // 将请最少选择一条数据返回
        this.$message({
          showClose: true,
          message: '请至少选择一个单位',
          type: 'warning',
          duration: 4000
        })
        return
      }
      if (this.selectMonth== '') {
        this.$message({
          showClose: true,
          message: '请选择月份',
          type: 'warning',
          duration: 4000
        })
        return
      }
        this.$confirm('此操作将区划数据同步, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          // this.$message({
          //   type: 'success',
          //   message: '同步成功!'
          // });
          this.handleSave()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消同步'
          });
        });
      // 打开弹窗
      this.editTableListLoading = true
      // 打开弹窗
      this.dialogVerifyFormVisible = true
    },
    // 保存方法
    handleSave(){
       // 获取当前 表格信息中的 序号
      const selection = this.$refs.singalTable.selection
      this.saveLoading = true
      // 创建一个集合数组
      const postIds = []
      // 将当前的存入 map 循环存入 返回给后台
       selection.forEach(item => {
        // 创建一个map
        const current = {}
        current['agencyId'] = item.id
        current['agencyCode'] = item.code
        current['agencyName'] = item.label
        current['isLeaf'] = item.isleaf
        current['levelNo'] = item.levelNo
        current['parentId'] = item.parentId
        current['salaryMonth'] = this.selectMonth
        
        // 将map 存入集合组数中
        postIds.push(current)
      })
    //  接口 插入或者保存
      insertAgencyLnIt(postIds).then((response) => {
        this.list = response.data.row
        this.dialogEditFormVisible = false
        this.$message({
          showClose: true,
          message: '同步成功',
          type: 'success',
          duration: 4000
        })
        this.saveLoading = false
        this.dialogVerifyFormVisible = false
        // 保存后调用刷新方法
        this.handleFilter()
      }).catch(() => {
        this.saveLoading = false
      })
    },
     // 保存成功后 刷新
    handleFilter() {
      this.getList()
      // this.initData();
    },
    // 获取当前值
  
      jobSearch() {
      this.getJobListByMonth();
    },
      initData(data) {
      //获取当前时间
      var now   = new Date();
      var monthn = now.getMonth()+1;
      var yearn  = now.getFullYear();
      this.selectMonth = yearn+"-"+monthn;
      this.selectUser = parseInt(sessionStorage.getItem("userid"));
      // this.getWeekJobList({
      //   userid: sessionStorage.getItem("userid"),
      //   weekid: "1"
      // });
      this.getJobListByMonth();
    },
    async getJobListByMonth(data) {
 
    },  
     // 导出
    outPutFile() {
      outPutProvinceReportList().then((response) => {
        const link = document.createElement("a");
        const objectUrl = URL.createObjectURL(response);
        link.href = objectUrl;
        link.download = "区划初始化.xls";
        link.click();
        URL.revokeObjectURL(objectUrl);
      });
    },
     // 上传文件
    uploadExcel(item) {
      const fileObj = item.file;
      const salaryMonth = this.selectMonth;
      // FormData 对象
      const form = new FormData();
      // 文件对象
      form.append("file", fileObj);
      form.append("salaryMonth",salaryMonth);
      provinceImport(form)
        .then((response) => {
          this.$message({
            showClose: true,
            message: "导入成功",
            type: "success",
            duration: 4000,
          });
          this.dialogImportFormVisible = false;
        })
        .then(() => {
          this.getList();
        });
    },
    // 导入
    importFile() {
      if (this.selectMonth== '') {
        this.$message({
          showClose: true,
          message: '请选择月份',
          type: 'warning',
          duration: 4000
        })
        return
      }
      this.dialogImportFormVisible = true;
    },
    selectable(row) {
      // 实发项和应发项复选框disable，不允许修改
    //   if (row.id == '0'|| row.code !=='0') { return false }{ return true}
        if (row.id === '0') { 
         return false;    
         } else {
               return true;   
     }         
    }
   }
}
</script>
<style lang="scss" scoped>
  .editFormDeviation {
    margin-left: 10%;
  }
  .viewFormDeviation {
    margin-left: 6%;
  }
    .formDeviation {
    margin-left: 5%;
  }
  ::v-deep .el-select {
    .el-input {
      height: auto !important;
    }
  }
  .el-input:not(.el-pagination__editor):not(.el-input--mini) {
    width: 204px;
    height: 40px !important;
    margin-left: 13px;
}
</style>
